<template>
  <span :endTime="endTime" :callback="callback" :endText="endText">
    <slot>
      {{ content }}
    </slot>
  </span>
</template>

<script lang="ts">
import { reactive, toRefs, defineComponent } from 'vue'
export default defineComponent({
  name: 'CountDown',
  props: {
    endTime: {
      type: String,
      default: ''
    },
    endText: {
      type: String,
      default: '已结束'
    },
    callback: {
      type: Function,
      default: null
    }
  },
  setup: (props) => {
    const state = reactive({
      content: ''
    })

    const countdowm = (timestamp: string) => {
      const timer = setInterval(function() {
        const nowTime = new Date()
        const t = Number(timestamp) - nowTime.getTime()
        if (t > 0) {
          const day = Math.floor(t / 86400000)
          const hour = Math.floor((t / 3600000) % 24)
          const min = Math.floor((t / 60000) % 60)
          const sec = Math.floor((t / 1000) % 60)
          const hourStr = hour < 10 ? '0' + hour : hour
          const minStr = min < 10 ? '0' + min : min
          const secStr = sec < 10 ? '0' + sec : sec
          let format = ''
          if (day > 0) {
            format = `${day} 天 ${hourStr} 小时 ${minStr} 分 ${secStr} 秒`
          }
          if (day <= 0 && hour > 0) {
            format = `${hour} 小时 ${min} 分 ${sec} 秒`
          }
          if (day <= 0 && hour <= 0) {
            format = `${min} 分 ${sec} 秒`
          }
          state.content = format
        } else {
          clearInterval(timer)
          state.content = props.endText
          _callback()
        }
      }, 1000)
    }
    const _callback = () => {
      if (props.callback && props.callback instanceof Function) {
        props.callback()
      }
    }

    countdowm(props.endTime)

    return {
      ...toRefs(state)
    }
  }
})
</script>

<style scoped>

</style>
